/**
 * 公共组件js
 * 为每个组件页面提供公共js方法
 * @author 003598
 */

/**
 * 添加String的format方法 替换对应位置的字符串
 * 
 * @param array[] 数组
 */
String.prototype.format = function(array) {
	return this.replace(/\{(\d+)\}/g, function(s, i) {
		return array[i];
	});
};

/** 页面通用方法接口*/
var base ={
	
		browser : {
	        versions : function() {
	            var u = navigator.userAgent, app = navigator.appVersion;
	            return {//移动终端浏览器版本信息
	                trident : u.indexOf('Trident') > -1, //IE内核
	                presto : u.indexOf('Presto') > -1, //opera内核
	                webKit : u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
	                gecko : u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
	                mobile : !!u.match(/AppleWebKit.*Mobile.*/)
	                || !!u.match(/AppleWebKit/), //是否为移动终端
	                ios : !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
	                android : u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
	                iPhone : u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
	                iPad : u.indexOf('iPad') > -1, //是否iPad
	                webApp : u.indexOf('Safari') == -1
	                //是否web应该程序，没有头部与底部
	            };
	        }(),
	        language : (navigator.browserLanguage || navigator.language).toLowerCase()
	},
		
	/** form表单提交 */
	setAction : function(action, method, formId, target) {
		var actionHref = '';
		if(basePath==null||basePath==''){
			if(action.indexOf('/')==0){
				actionHref = action;
			}else{
				actionHref = "/" + action;
			}
		}else{
			actionHref = basePath + "/" +action;
		}
		method = method || "post";
		formId = "#" + (formId || "mainForm");
		target = target || "_self";
		$(formId).attr("action", actionHref).attr("method", method).attr("target",
				target).submit();
	},
	
	/** get提交*/
	getAction:function(action){
		if(basePath==null||basePath==''){
			if(action.indexOf('/')==0){
				window.location.href = action;
			}else{
				window.location.href = "/" + action;
			}
		}else{
			window.location.href= basePath + "/" +action;
		}
	},
	
	/** 验证input是否为空*/
	validInputNull: function($erroreDom){
		var flag = false;
		$('input:visible').each(function() {
			var _val = $(this).val();
			var _tip = $(this).attr('tip');
			if (!_val || '' === _val){
				$erroreDom.empty().append('<span>*</span><span>'+_tip+'</span>').show();
				flag = true;
				return false;
			}
		});
		return flag;
	},

	/** 验证input是否为空*/
	isInputNull: function(){
		var flag = false;
		$('input:visible').each(function() {
			var _val = $(this).val();
			var _tip = $(this).attr('tip');
			if (!_val || '' === _val){
				flag = true;
				
				Message.showMessage({
					text: _tip,
					textSize: 'left',
					titleSize: 'left'
				});
				
				return false;
			}
		});
		return flag;
	},
	
	/** ajax公共方法 */
	AJAX_POST : function(action, data,type,callback,async) {
		var actionHref = '';
		if(basePath==null||basePath==''){
			if(action.indexOf('/')==0){
				actionHref = action;
			}else{
				actionHref = "/" + action;
			}
		}else{
			actionHref = basePath + "/" +action;
		}
		var dataObj = {};
		if (data){
			dataObj = data;
		}
		if(!type){
			type = 'json';
		}
		var as = async || true;
		if(async&&async=='false'){
			as = false;
		}else if(async&&async=='true'){
			as = true;
		}
		$.ajax({
			url : actionHref,
			data : dataObj,
			type : 'post',
			dataType : type,
			async : as,      // 取消异步请求
			beforeSend : function() {
				
			},
			success : function(o) {
				if (callback && $.isFunction(callback)) {
					callback(o);
				}
			},
			complete : function(XMLHttpRequest, textStatus) {
			},
			error : function() {
			}
			
		});
	},
	
	/** 验证手机号码*/
	vailNum:function(value){
		/** 手机号 */
		var strArray = [// 移动
		                '139', '138', '137', '136', '135', '134', '147', '150', '151', '152', '157', '158', '159', '182', '183', '184', '187', '188',
		                // 联通
		                '130', '131', '132', '155', '156', '185', '186', '145',
		                // 电信
		                '133', '153', '180', '181', '189', '177'];
		
		var mobile = new RegExp( '^(' + strArray.join('|') + ')\\d{8}$' ); 
		
		return mobile.test($.trim(value)); 
		
	},
	
};


var PM = PM || {};

PM.More = {};
PM.More.Initialize = function(config)
{
	config = config || {};

	PM.More._url = config.url;
	PM.More._query = config.query || {};
	PM.More._gridview = $(config.gridview);
	
	PM.More._query.size = config.size || 10;
	PM.More._query._index = config.index || 0;
	
	$(window).scroll(function(){
		var scrollTop = $(this).scrollTop(),
			scrollHeight = $(document).height(),
			windowHeight = $(this).height();
	
		if(scrollTop + windowHeight == scrollHeight){
			PM.More._Load();
		}
	});
};

PM.More._Load = function()
{
	PM.More._query._index++;
	alert(JSON.stringify(PM.More._query));
	jQuery.ajax(
	{
		url: PM.More._url,
		type: 'GET',
		dataType: 'HTML',
		data: PM.More._query,
		success: function(result)
		{
			PM.More._gridview.append(result);
			alert(result);
		}
	});
};



/*$(function(){
	var timeUtil = new MrYangUtil();
	console.log(timeUtil.getCurrentDate());
	console.log(timeUtil.getCurrentWeek());
	console.log(timeUtil.getCurrentMonth());
	console.log(timeUtil.getCurrentSeason());
	console.log("getPreviousMonth:" + timeUtil.getPreviousMonth());
	console.log(timeUtil.getPreviousWeek());
	console.log(timeUtil.getPreviousSeason());
	console.log(timeUtil.getPreviousYear());
});*/

//对Date的扩展，将 Date 转化为指定格式的String 
//月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
//年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
//例子： 
//(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
//(new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.Format = function(fmt) { 
	var o = { 
		 "M+" : this.getMonth()+1,                 //月份 
		 "d+" : this.getDate(),                    //日 
		 "h+" : this.getHours(),                   //小时 
		 "m+" : this.getMinutes(),                 //分 
		 "s+" : this.getSeconds(),                 //秒 
		 "q+" : Math.floor((this.getMonth()+3)/3), //季度 
		 "S"  : this.getMilliseconds()             //毫秒 
	}; 
	if(/(y+)/.test(fmt)) {
		
	}
	 fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
	for(var k in o) {
		
		if(new RegExp("("+ k +")").test(fmt)){
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); 
		} 
	}
	return fmt; 
}

var MrYangUtil=function(){ 
    // 获取当前日期
    this.getCurrentDate=function(){ 
        return new Date(); 
    }; 
    
    this.string2Date = function(str){
    	
        str =  str.replace(/-/g,"/");
       //// str =  str.replace("T"," "); 
        var oDate1 = new Date(str);
        
        return oDate1;
    	
    }
    
    this.getDateStr = function(AddDayCount) { 
    	var dd =  this.getCurrentDate();
    	dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期 
    	var y = dd.getFullYear(); 
    	var m = dd.getMonth()+1;//获取当前月份的日期 
    	var d = dd.getDate(); 
    	return y+"/"+m+"/"+d; 
    },
    
    // 获取今天的日期
    this.getToday = function(){
    	return this.getDateStr(0);
    },
    
    // 获取昨天的日期
    this.getPreviousDay = function(){
    	return this.getDateStr(-1);
    }
     
    // 获取当期星期的日期
    this.getCurrentWeek=function(){ 
        //起止日期数组  
        var startStop=new Array(); 
        //获取当前时间  
        var currentDate=this.getCurrentDate(); 
        //返回date是一周中的某一天  
        var week=currentDate.getDay(); 
        //返回date是一个月中的某一天  
        var month=currentDate.getDate(); 
        //一天的毫秒数  
        var millisecond=1000*60*60*24; 
        //减去的天数  
        var minusDay=week!=0?week-1:6; 
        //alert(minusDay);  
        //本周 周一  
        var monday=new Date(currentDate.getTime()-(minusDay*millisecond)); 
        //本周 周日  
        var sunday=new Date(monday.getTime()+(6*millisecond)); 
        //添加本周时间  
        startStop.push(monday.Format("yyyy-MM-dd"));//本周起始时间  
        //添加本周最后一天时间  
        startStop.push(sunday.Format("yyyy-MM-dd"));//本周终止时间  
        //返回  
        return startStop; 
    }; 
     
    // 获取当期月的日期
    this.getCurrentMonth=function(){ 
        //起止日期数组  
        var startStop=new Array(); 
        //获取当前时间  
        var currentDate=this.getCurrentDate(); 
        //获得当前月份0-11  
        var currentMonth=currentDate.getMonth(); 
        //获得当前年份4位年  
        var currentYear=currentDate.getFullYear(); 
        //求出本月第一天  
        var firstDay=new Date(currentYear,currentMonth,1); 
        //当为12月的时候年份需要加1  
        //月份需要更新为0 也就是下一年的第一个月  
        if(currentMonth==11){ 
            currentYear++; 
            currentMonth=0;//就为  
        }else{ 
            //否则只是月份增加,以便求的下一月的第一天  
            currentMonth++; 
        } 
        //一天的毫秒数  
        var millisecond=1000*60*60*24; 
        //下月的第一天  
        var nextMonthDayOne=new Date(currentYear,currentMonth,1); 
        //求出上月的最后一天  
        var lastDay=new Date(nextMonthDayOne.getTime()-millisecond); 
        //添加至数组中返回  
        startStop.push(firstDay.Format("yyyy-MM-dd")); 
        startStop.push(lastDay.Format("yyyy-MM-dd")); 
        //返回  
        return startStop; 
    }; 
     
    this.getQuarterSeasonStartMonth=function(month){ 
        var quarterMonthStart=0; 
        var spring=0; //春  
        var summer=3; //夏  
        var fall=6;   //秋  
        var winter=9;//冬  
        //月份从0-11  
        if(month<3){ 
            return spring; 
        } 
        if(month<6){ 
            return summer; 
        } 
        if(month<9){ 
            return fall; 
        } 
        return winter; 
    }; 
     
    this.getMonthDays=function(year,month){ 
        //本月第一天 1-31  
        var relativeDate=new Date(year,month,1); 
        //获得当前月份0-11  
        var relativeMonth=relativeDate.getMonth(); 
        //获得当前年份4位年  
        var relativeYear=relativeDate.getFullYear(); 
        //当为12月的时候年份需要加1  
        //月份需要更新为0 也就是下一年的第一个月  
        if(relativeMonth==11){ 
            relativeYear++; 
            relativeMonth=0; 
        }else{ 
            //否则只是月份增加,以便求的下一月的第一天  
            relativeMonth++; 
        } 
        //一天的毫秒数  
        var millisecond=1000*60*60*24; 
        //下月的第一天  
        var nextMonthDayOne=new Date(relativeYear,relativeMonth,1); 
        //返回得到上月的最后一天,也就是本月总天数  
        return new Date(nextMonthDayOne.getTime()-millisecond).getDate(); 
    }; 
     
    // 获取当期季度的日期
    this.getCurrentSeason=function(){ 
        //起止日期数组  
        var startStop=new Array(); 
        //获取当前时间  
        var currentDate=this.getCurrentDate(); 
        //获得当前月份0-11  
        var currentMonth=currentDate.getMonth(); 
        //获得当前年份4位年  
        var currentYear=currentDate.getFullYear(); 
        //获得本季度开始月份  
        var quarterSeasonStartMonth=this.getQuarterSeasonStartMonth(currentMonth); 
        //获得本季度结束月份  
        var quarterSeasonEndMonth=quarterSeasonStartMonth+2; 
        //获得本季度开始的日期  
        var quarterSeasonStartDate=new Date(currentYear,quarterSeasonStartMonth,1); 
        //获得本季度结束的日期  
        var quarterSeasonEndDate=new Date(currentYear,quarterSeasonEndMonth,this.getMonthDays(currentYear, quarterSeasonEndMonth)); 
        //加入数组返回  
        startStop.push(quarterSeasonStartDate.Format("yyyy-MM-dd")); 
        startStop.push(quarterSeasonEndDate.Format("yyyy-MM-dd")); 
        //返回  
        return startStop; 
    }; 
    // 获取当期年的日期
    this.getCurrentYear=function(){ 
        //起止日期数组  
        var startStop=new Array(); 
        //获取当前时间  
        var currentDate=this.getCurrentDate(); 
        //获得当前年份4位年  
        var currentYear=currentDate.getFullYear(); 
        //本年第一天  
        var currentYearFirstDate=new Date(currentYear,0,1); 
        //本年最后一天  
        var currentYearLastDate=new Date(currentYear,11,31); 
        //添加至数组  
        startStop.push(currentYearFirstDate.Format("yyyy-MM-dd")); 
        startStop.push(currentYearLastDate.Format("yyyy-MM-dd")); 
        //返回  
        return startStop; 
    }; 
     
    this.getPriorMonthFirstDay=function(year,month){ 
        //年份为0代表,是本年的第一月,所以不能减  
        if(month==0){ 
            month=11;//月份为上年的最后月份  
            year--;//年份减1  
            return new Date(year,month,1); 
        } 
        //否则,只减去月份  
        month--; 
        return new Date(year,month,1);; 
    }; 
     
    this.getPreviousMonth=function(){ 
        //起止日期数组  
        var startStop=new Array(); 
        //获取当前时间  
        var currentDate=this.getCurrentDate(); 
        //获得当前月份0-11  
        var currentMonth=currentDate.getMonth(); 
        //获得当前年份4位年  
        var currentYear=currentDate.getFullYear(); 
        //获得上一个月的第一天  
        var priorMonthFirstDay=this.getPriorMonthFirstDay(currentYear,currentMonth); 
        //获得上一月的最后一天  
        var priorMonthLastDay=new Date(priorMonthFirstDay.getFullYear(),priorMonthFirstDay.getMonth(),this.getMonthDays(priorMonthFirstDay.getFullYear(), priorMonthFirstDay.getMonth())); 
        //添加至数组  
        startStop.push(priorMonthFirstDay.Format("yyyy-MM-dd")); 
        startStop.push(priorMonthLastDay.Format("yyyy-MM-dd")); 
        //返回  
        return startStop; 
    }; 
     
    this.getPreviousWeek=function(){ 
        //起止日期数组  
        var startStop=new Array(); 
        //获取当前时间  
        var currentDate=this.getCurrentDate(); 
        //返回date是一周中的某一天  
        var week=currentDate.getDay(); 
        //返回date是一个月中的某一天  
        var month=currentDate.getDate(); 
        //一天的毫秒数  
        var millisecond=1000*60*60*24; 
        //减去的天数  
        var minusDay=week!=0?week-1:6; 
        //获得当前周的第一天  
        var currentWeekDayOne=new Date(currentDate.getTime()-(millisecond*minusDay)); 
        //上周最后一天即本周开始的前一天  
        var priorWeekLastDay=new Date(currentWeekDayOne.getTime()-millisecond); 
        //上周的第一天  
        var priorWeekFirstDay=new Date(priorWeekLastDay.getTime()-(millisecond*6)); 
        //添加至数组  
        startStop.push(priorWeekFirstDay.Format("yyyy-MM-dd")); 
        startStop.push(priorWeekLastDay.Format("yyyy-MM-dd")); 
        return startStop; 
    }; 
     
    this.getPriorSeasonFirstDay=function(year,month){ 
        var quarterMonthStart=0; 
        var spring=0; //春  
        var summer=3; //夏  
        var fall=6;   //秋  
        var winter=9;//冬  
        //月份从0-11  
        switch(month){//季度的其实月份  
        case spring: 
            //如果是第一季度则应该到去年的冬季  
              year--; 
              month=winter; 
            break; 
        case summer: 
            month=spring; 
            break; 
        case fall: 
            month=summer; 
            break; 
        case winter: 
            month=fall; 
            break; 
        }; 
        return new Date(year,month,1); 
    }; 
     
    this.getPreviousSeason=function(){ 
        //起止日期数组  
        var startStop=new Array(); 
        //获取当前时间  
        var currentDate=this.getCurrentDate(); 
        //获得当前月份0-11  
        var currentMonth=currentDate.getMonth(); 
        //获得当前年份4位年  
        var currentYear=currentDate.getFullYear(); 
        //上季度的第一天  
        var priorSeasonFirstDay=this.getPriorSeasonFirstDay(currentYear, currentMonth); 
        //上季度的最后一天  
        var priorSeasonLastDay=new Date(priorSeasonFirstDay.getFullYear(),priorSeasonFirstDay.getMonth()+2,this.getMonthDays(priorSeasonFirstDay.getFullYear(), priorSeasonFirstDay.getMonth()+2)); 
        //添加至数组  
        startStop.push(priorSeasonFirstDay.Format("yyyy-MM-dd")); 
        startStop.push(priorSeasonLastDay.Format("yyyy-MM-dd")); 
        return startStop; 
    }; 
     
    this.getPreviousYear=function(){ 
        //起止日期数组  
        var startStop=new Array(); 
        //获取当前时间  
        var currentDate=this.getCurrentDate(); 
        //获得当前年份4位年  
        var currentYear=currentDate.getFullYear(); 
            currentYear--; 
        var priorYearFirstDay=new Date(currentYear,0,1); 
        var priorYearLastDay=new Date(currentYear,11,1); 
        //添加至数组  
        startStop.push(priorYearFirstDay.Format("yyyy-MM-dd")); 
        startStop.push(priorYearLastDay.Format("yyyy-MM-dd")); 
        return startStop; 
    };
};
